//这是处理获取所有跟文章有关的控制器

const postsModel = require('../model/postsModel');
const moment = require('moment');
// 获取所有文章
exports.getAllPosts = (req,res)=>{
   // 获取参数
   let obj = req.query
   // 调用数据模块获取数据
   postsModel.getAllPosts(obj,(err,data)=>{
      if(err){
         res.json({code:400,msg:'can not find data'})
      }else{
         //转换日期格式
         // for(var i = 0 ; i < data.length;i ++){
         //    data[i].created = moment(data[i].created).format('YYYY-MM-DD HH-mm-ss')
         // }
         res.json({code:200,msg:'success',data})
      }
   })
}
// 添加文章
exports.addPost = (req,res)=>{
   // 获取数据
   let obj = req.body
   obj.id = null
   obj.user_id = req.session.currentUser.id
   obj.views = 0
   obj.likes = 0
   // 调用数据模块的方法
   postsModel.addPost(obj,(err)=>{
      if(err){
         console.log(err)
         res.json({code:400,msg:'failed to add new article'})
      }else{
         res.json({code:200,msg:'succeed to add new article'})
      }
   })
}
// 通过id获取文章
exports.getPostById = (req,res)=>{
   // 获取id
   let id = req.query.id
   // 调用数据模块
   postsModel.getPostById(id,(err,data)=>{
      if(err){
         res.json({code:400,msg:'faild to get information'})
      }else{
         data.created = moment(data.created).format('YYYY-MM-DDTHH:mm')
         res.json({code:200,msg:'succeed to get data',data})
      }
   })
}

// 通过id编辑文章
exports.editPostById = (req,res)=>{
   // 接收参数
   let obj = req.body
   // console. log(obj)
   // 调用数据模块
   postsModel.editPostById(obj,(err)=>{
      if(err){
         // console.log(err);
         res.json({code:400,msg:'failed to edit'})
      }else{
         res.json({code:200,msg:'succeed to edit'})
      }
   })
}

// 通过id删除文章
exports.deletePostById = (req,res)=>{
   // 接收id
   let id = req.query.id
   console.log(id)
   // 调用数据模块
   postsModel.deletePostById(id,(err)=>{
      if(err){
         res.json({code:400,msg:'failed to delete'})
      }else{
         res.json({code:200,msg:'succeed to delete'})
      }
   })
}